package com.dm.cloud.utils.mingexcel.worker;

import com.dm.cloud.utils.mingexcel.entity.TransferItem;
import lombok.Data;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Data
public class TransferWorker {

    String methodName = "initItems";

    //对应转换关系
    private Map<Integer, TransferItem[]> formaters = new HashMap<>();

    public TransferWorker(){ }

    public TransferWorker(Map<Integer, TransferItem[]> formaters){
        this.formaters = formaters;
    }

    /**
     * 查找转换值
     * @param showOriginWhenNotExsit 转换值不存在时是否展示原始值
     * @param mapKey
     * @param key
     * @return
     */
    public String transferToExcel(boolean showOriginWhenNotExsit,Integer mapKey,Object key){
        //默认返回原始值
        TransferItem defaultItem = new TransferItem();
        if(showOriginWhenNotExsit){
            defaultItem.setValue(String.valueOf(key));
        }else{
            defaultItem.setValue("");
        }
        if(null != formaters && formaters.size()>0 && formaters.containsKey(mapKey)){
            return Arrays.asList(formaters.get(mapKey)).stream().filter(e->key.equals(e.getKey())).findFirst().orElse(defaultItem).getValue();
        }
        return defaultItem.getValue();
    }

    /**
     * 查找转换值的key
     * @param mapKey
     * @param value
     * @param <T>
     * @return
     */
    public <T> T transferFromExcel(Integer mapKey,String value){
        if(null != formaters && formaters.size()>0 && formaters.containsKey(mapKey)){
            Optional<TransferItem> item = Arrays.asList(formaters.get(mapKey)).stream().filter(e->value.equals(e.getValue())).findFirst();
            if(item.isPresent()){
                Object key = item.get().getKey();
                return (T)key;
            }
        }
        return null;
    }

    /**
     * 获取下拉列表的展示值数组
     * @param mapKey
     * @return
     */
    public String[] getValueArray(Integer mapKey){
        if(formaters.containsKey(mapKey)){
            TransferItem[] items = formaters.get(mapKey);
            if(null!=items) {
                String[] result = new String[items.length];
                for (int i = 0; i < items.length; i++) {
                    result[i] = items[i].getValue();
                }

                return result;
            }
        }
        return null;
    }

    public void setFormater(Map<Integer, TransferItem[]> formaters) {
        this.formaters = formaters;
    }

    public void addFormater(Integer index, TransferItem[] formater) {
        this.formaters.put(index,formater);
    }
}
